package org.ioriframework.boot.job.task;

import javax.annotation.Resource;

import org.ioriframework.boot.async.producer.ITaskProducer;
import org.ioriframework.boot.async.vo.AsyncMessageVO;
import org.ioriframework.boot.core.util.StringUtils;
import org.ioriframework.boot.job.vo.JobTraceVO;
import org.ioriframework.boot.job.vo.JobVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * Rest任务处理器
 * @author iori
 *
 */
@Component("restJobProcesser")
public class RestJobProcesser {
	
	public final static int FINAL_STATUS_SUCCESS = 1;
	
	public final static int FINAL_STATUS_FAIL = 0;
	
	private static Logger log = LoggerFactory.getLogger(RestJobProcesser.class);

	@Resource(name="jobRestTemplate")
	private RestTemplate jobRestTemplate;
	
	@Resource(name="fastTaskProducer")
	private ITaskProducer fastTaskProducer;
	
	public void process(JobVO jobVO) {
		String returnValue = null;
		// 状态默认成功
		Integer finalStatus = FINAL_STATUS_SUCCESS;
		Long startTime = System.currentTimeMillis();
		try {
			if (!StringUtils.isNullOrEmpty(jobVO.getJobContent())) {
				returnValue = jobRestTemplate.getForObject(jobVO.getJobContent(), String.class);
			} else {
				returnValue = "no job content.";
			}
		} catch(Exception e) {
			finalStatus = FINAL_STATUS_FAIL;
			// 任务执行异常，将异常信息写入返回值中
			returnValue = e.getMessage();
		} finally {
			log.debug("job[{}] processed, return {}", jobVO.getJobName(), returnValue);
			JobTraceVO jobTraceVO = new JobTraceVO();
			jobTraceVO.setJobId(jobVO.getJobId());
			jobTraceVO.setFinalStatus(finalStatus);
			jobTraceVO.setReturnValue(returnValue);
			jobTraceVO.setTotalTime(System.currentTimeMillis() - startTime);
			AsyncMessageVO vo1 = new AsyncMessageVO("jobTraceMessage");
			vo1.setContent(jobTraceVO);
			fastTaskProducer.createTask(vo1);
		}
	}
}
